package com.azzcs.juc.product_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: wzg
 * @Date: 2021/6/15 下午2:39
 */
public class Q {

    private final String[] buffer = new String[10];

    private int productIndex, consumerIndex, size;

    private ReentrantLock lock = new ReentrantLock();

    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public void put(String data) {
        lock.lock();
        try {
            while (size >= buffer.length) {
                notFull.await();
            }
            buffer[productIndex++] = data;
            if (productIndex == buffer.length) {
                productIndex = 0;
            }
            size++;
            notEmpty.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public String get() {
        lock.lock();
        String result = null;
        try {
            while (size <= 0) {
                notEmpty.await();
            }
            result = buffer[consumerIndex++];
            if (consumerIndex == buffer.length) {
                consumerIndex = 0;
            }
            size--;
            notFull.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return result;
    }

}
